package com.guhecloud.step.definition.runtime;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.atomic.AtomicBoolean;

@Component
@Slf4j
public class CenterBootStrap implements ApplicationListener<ContextRefreshedEvent>, ApplicationContextAware {
    private AtomicBoolean once = new AtomicBoolean();

    @Resource
    private RegistryFactory registryFactory;

    @Autowired(required = false)
    private IStartupListener startupListener;

    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (!once.compareAndSet(false, true)) {
            return;
        }

        long t0 = System.nanoTime();
        registryFactory.register(applicationContext);

        this.applicationContext = applicationContext;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        if (contextRefreshedEvent.getApplicationContext().equals(applicationContext)) {

            if (startupListener != null) {
                startupListener.onStartComplete();
            }
        } else {
            log.info("Spring reloaded complete!");
        }
    }

    static ApplicationContext applicationContext() {
        return applicationContext;
    }
}
